package com.itheima.pinda.zuul.filter;

import cn.hutool.core.util.StrUtil;
import com.itheima.pinda.base.R;
import com.itheima.pinda.common.adapter.IgnoreTokenConfig;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 基础 网关过滤器
 * @Author: ysf
 * @CreateTime: 2024-11-14  14:12
 * @Version: 1.0
 */
@Slf4j
public abstract class BaseFilter extends ZuulFilter {

    @Value("${server.servlet.context-path}")
    protected String zuulPrefix;

    /**
     * 过滤接口是否需要忽略
     * @return boolean
     */
    public boolean getIgnoreToken() {
        RequestContext rc = RequestContext.getCurrentContext();
        HttpServletRequest request = rc.getRequest();
        String url = request.getRequestURI();
        // /api/auth/xxx/xxx
        url = StrUtil.subSuf(url, zuulPrefix.length());
        // /auth/xxx/xxx
        url = StrUtil.subSuf(url, url.indexOf("/", 1));
        boolean ignoreToken = IgnoreTokenConfig.isIgnoreToken(url);
        return ignoreToken;
    }


    /**
     * 网关异常处理 没有权限网关抛出异常，不再去路由，直接返回异常信息给前端
     * @param errMsg
     * @param errCode
     * @param httpStatusCode
     * @return void
     */
    protected void errorResponse(String errMsg, int errCode, int httpStatusCode) {
        //封装异常信息
        R toeknError = R.fail(errCode, errMsg);
        RequestContext currentContext = RequestContext.getCurrentContext();
        currentContext.setResponseStatusCode(httpStatusCode);
        //设置回写响应头信息
        currentContext.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8");
        if (currentContext.getResponseBody() == null) {
            //返回响应体
            currentContext.setResponseBody(toeknError.toString());
            //不进行路由，直接返回
            currentContext.setSendZuulResponse(false);
        }
    }


}
